/**
 * @description 后台服务工作进程，处理翻译请求和消息传递
 * @author LingXiYi
 */

import { MD5 } from './utils/md5.js';

// 支持的语言列表
const SUPPORTED_LANGUAGES = {
  'zh': '中文',
  'en': '英语',
  'ja': '日语',
  'ko': '韩语',
  'fr': '法语',
  'de': '德语'
};

/**
 * @description 初始化服务工作进程
 */
async function initialize() {
  // 设置默认配置
  const defaultConfig = {
    enabled: false,
    targetLang: 'zh'
  };
  
  const config = await chrome.storage.local.get(['enabled', 'targetLang']);
  if (!config.enabled) {
    await chrome.storage.local.set(defaultConfig);
  }
}

/**
 * @description 处理翻译请求
 * @param {string} text - 待翻译文本
 * @param {string} targetLang - 目标语言代码
 * @returns {Promise<Object>} 翻译结果
 */
async function handleTranslation(text, targetLang) {
  const maxRetries = 3;
  let retryCount = 0;
  
  while (retryCount < maxRetries) {
    try {
      const appid = '20250211002270594';
      const key = 'AqPTDPvgy6Rp5L1It0nU';
      const salt = new Date().getTime();
      const sign = MD5(appid + text + salt + key);
      
      const url = `https://api.fanyi.baidu.com/api/trans/vip/translate?q=${encodeURIComponent(text)}&from=auto&to=${targetLang}&appid=${appid}&salt=${salt}&sign=${sign}`;
      
      const response = await fetch(url);
      const result = await response.json();
      
      // 检查错误码
      if (result.error_code) {
        throw new Error(`百度翻译错误: ${result.error_msg}`);
      }
      
      if (result.trans_result && result.trans_result.length > 0) {
        return {
          translatedText: result.trans_result[0].dst,
          sourceLang: result.from,
          targetLang: targetLang
        };
      } else {
        throw new Error('翻译结果为空');
      }
    } catch (error) {
      retryCount++;
      if (retryCount === maxRetries) {
        console.error('翻译出错:', error);
        return {
          error: '翻译服务暂时不可用，请稍后重试'
        };
      }
      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
    }
  }
}

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'translate') {
    handleTranslation(request.text, request.targetLang)
      .then(result => sendResponse(result))
      .catch(error => sendResponse({ error: error.message }));
    return true; // 保持消息通道开启
  }
});

// 初始化
initialize(); 